<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;
use App\Log;
use App\Service\UserService;
use Hyperf\Cache\Cache;
use Hyperf\Coroutine\Coroutine;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Coroutine\WaitGroup;
use function Swoole\Coroutine\go;
use function Swoole\Coroutine\defer;

#[Controller]
class UserController extends AbstractController
{

    // 其实就想当于 new UserService()
    #[Inject]
    private UserService $userService;

    // Hyperf 会自动为此方法生成一个 /user/abc 的路由，允许通过 GET 或 POST 方式请求
//    #[RequestMapping(path: "abc", methods: "get,post")]
    #[RequestMapping(path: "abc", methods: "get")]
    public function abc()
    {
        $mid = $this->request->input('mid', 123);
        $method = $this->request->getMethod();
        $mid=$this->userService->getUserInfo($mid);
        $this->logger->info('user abc'.date('Y-m-d H:i:s'));

        $wg = new WaitGroup();
        $wg->add(2);
        go(function () use ($wg) {
            defer(function () {
                Log::get('mypay','mypay')->info('user_co1 out:'.time().'_coid:'. Coroutine::id());
            });
            Log::get('mypay','mypay')->info('user_co1 into:'.time().'_coid:'. Coroutine::id());
            Coroutine::sleep(10);
            $wg->done();
        });
        go(function () use ($wg) {
            defer(function () {
                Log::get('mypay','mypay')->info('user_co2 out:'.time().'_coid:'. Coroutine::id());
            });
            Log::get('mypay','mypay')->info('user_co2 into:'.time().'_coid:'. Coroutine::id());
            Coroutine::sleep(10);
            $wg->done();
        });
        Log::get('mypay','mypay')->info('user_return1:'.time());
        // 等待协程 A 和协程 B 运行完成
        $wg->wait();
        Log::get('mypay','mypay')->info('user_return2:'.time());

        return [
            'method' => $method,
            'message' => "Hello {$mid}.",
        ];
    }
}
